#include "HttpPostRunnable.h"

void HttpPostRunnable::run()
{
    if (!curl)
    {
        return;
    }
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &HttpPostRunnable::response);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) this);
    struct curl_slist *headers = nullptr;
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str());
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 6);//接收数据时超时设置，如果10秒内数据未接收完，直接退出
    CURLcode res = curl_easy_perform(curl);

    postResult = CURLE_OK == res;
}
HttpPostRunnable::HttpPostRunnable(CURL *m_curl)
    : curl(m_curl), postResult(false)
{

}
HttpPostRunnable::~HttpPostRunnable() = default;

bool HttpPostRunnable::getResult() const
{
    return postResult;
}

void HttpPostRunnable::setUrl(const std::string &url)
{
    this->url = url;
}
void HttpPostRunnable::setData(const std::string &data)
{
    this->data = data;
}
void HttpPostRunnable::setResponseCallback(const HttpPostRunnable::Response &response)
{
    responseCallback = response;
}
size_t HttpPostRunnable::response(char *ptr, size_t size, size_t nmemb, void *userdata)
{
    size_t realSize = size * nmemb;
    auto *point = static_cast<HttpPostRunnable *>(userdata);
    if (point == nullptr)
    {
        return realSize;
    }
    std::string responseData(ptr, realSize);
    point->responseCallback(responseData);
    return realSize;
}
